package com.junzhiit.nengji.cms.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.bo.OrdersGoodsBO;
import com.junzhiit.nengji.bo.OrdersRefundBO;
import com.junzhiit.nengji.bo.SendPhoneMessageBO;
import com.junzhiit.nengji.cms.service.OrdersRefundService;
import com.junzhiit.nengji.cms.web.exception.RefundMoneyFailException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.cms.web.util.tools.NumberUtils;
import com.junzhiit.nengji.cms.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.cms.web.util.wechat.bean.RefundOrder;
import com.junzhiit.nengji.cms.web.util.wechat.bean.RefundResult;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.OrdersRefundVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersGoodsDAO;
import com.junzhiit.nengji.dao.OrdersRefundDAO;
import com.junzhiit.nengji.dao.ShopClientDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Orders;
import com.junzhiit.nengji.model.OrdersGoods;
import com.junzhiit.nengji.model.OrdersRefund;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopClient;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.OrderStatus;
import com.junzhiit.nengji.model.enums.OrdersRefundStatus;
import com.junzhiit.nengji.model.enums.PayWay;

@Service
public class OrdersRefundServiceImpl implements OrdersRefundService{

	@Autowired
	private OrdersRefundDAO ordersRefundDAO;
	
	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;
	
	@Autowired
	private OrdersDAO ordersDAO;
	
	@Autowired
	private OrdersGoodsDAO ordersGoodsDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private ShopClientDAO shopClientDAO;
	
	@Override
	public Map<String, Object> findAll(DataTablesParamVO dtp, OrdersRefundVO ordersRefundVO) {
		OrdersRefundBO ordersRefundBO = new OrdersRefundBO();
		BeanUtils.copyProperties(ordersRefundVO,ordersRefundBO);
		
		if (StringUtils.isBlank(ordersRefundVO.getShopId())) {
			SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
					.getHash(DIYKey.getSessionHashKey(ordersRefundVO.getSessionId()), SystemUserSessionVO.class);
			if(StringUtils.isNotBlank(systemUserSessionVO.getSystemId())){
				Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
//				Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
//				if (shop == null && chain == null) {
//					throw new ShopNotFoundException("店铺/品牌不存在");
//				}
				if (shop == null) {
					throw new ShopNotFoundException("店铺不存在");
				}
				if(shop != null){
					ordersRefundBO.setShopId(systemUserSessionVO.getSystemId());
//				}else if(chain != null){
//					ordersBO.setChainId(systemUserSessionVO.getSystemId());
				}
			}
		}
		
		List<OrdersRefundBO> list = ordersRefundDAO.findAll(ordersRefundBO, dtp.getStart(), dtp.getLength());
		int totalCount = ordersRefundDAO.getTotalCount(ordersRefundBO);
		
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}

	@Override
	public ResultVO update(OrdersRefundVO ordersRefundVO) {
		ResultVO result = new ResultVO();
		Date now = new Date();
		OrdersRefund or = ordersRefundDAO.query(ordersRefundVO.getId());
		OrdersGoods og = ordersGoodsDAO.query(or.getOrdersGoodsId());
		if(ordersRefundVO.getStatus()==OrdersRefundStatus.SHOP_AGREE.toIntStatus()){
			or.setShopDealTime(now);
		}
		if(ordersRefundVO.getStatus()==OrdersRefundStatus.SHOP_REJECT.toIntStatus()){
			or.setCompleteTime(now);
			or.setShopDealTime(now);
			or.setFailReason(ordersRefundVO.getFailReason());
			og.setIsRefundMoney(Is.NO.toIntValue());
			User user=userDAO.query(or.getUserId());
			String mobilePhone=user.getMobilePhone();
			if(StringUtils.isNotBlank(mobilePhone)){
				SendPhoneMessageBO spmb=new SendPhoneMessageBO();
				spmb.setAuditFailDescription(ordersRefundVO.getFailReason());
				spmb.setMobilePhone(mobilePhone);
				spmb.setSmsModel(SmsUtil.ORDERS_REFUND_AUDIT_FAIL);
				SmsUtil.sendPhoneMessage(spmb);
			}
		}
		if(ordersRefundVO.getStatus()==OrdersRefundStatus.PLATFORM_REJECT.toIntStatus()){
			or.setFailReason(ordersRefundVO.getFailReason());
			or.setPlatformTime(now);
			or.setCompleteTime(now);
			og.setIsRefundMoney(Is.NO.toIntValue());
			User user=userDAO.query(or.getUserId());
			String mobilePhone=user.getMobilePhone();
			if(StringUtils.isNotBlank(mobilePhone)){
				SendPhoneMessageBO spmb=new SendPhoneMessageBO();
				spmb.setAuditFailDescription(ordersRefundVO.getFailReason());
				spmb.setMobilePhone(mobilePhone);
				spmb.setSmsModel(SmsUtil.ORDERS_REFUND_AUDIT_FAIL);
				SmsUtil.sendPhoneMessage(spmb);
			}
		}
		or.setStatus(ordersRefundVO.getStatus());
		ordersGoodsDAO.update(og);
		ordersRefundDAO.update(or);
		return result;
	}

	@Override
	public ResultVO refund(String id) {
		ResultVO result = new ResultVO();
		boolean flag = true;
		OrdersRefund ordersRefund = ordersRefundDAO.query(id);
		OrdersGoods ordersGoods = ordersGoodsDAO.query(ordersRefund.getOrdersGoodsId());
		Orders orders = ordersDAO.query(ordersGoods.getOrderId());
		RefundResult refundResult = null;
		UserConfig userConfig = userConfigDAO.getUserConfig(orders.getUserId());
		if(orders.getPayWay()==PayWay.WECHAT.toIntValue()){//微信支付退款
			RefundOrder refundOrder = new RefundOrder();
			refundOrder.setTransactionId(orders.getTransactionNumber());
			refundOrder.setOutRefundNo(NumberUtils.getMchBillno());
			refundOrder.setTotalFee(Math.round(orders.getPayMoney()*100));
			refundOrder.setRefundFee(Math.round(ordersRefund.getMoney()*100));
			refundOrder.setRefundDesc(ordersRefund.getReason());
			refundResult = WeChatUtils.refund(refundOrder);
			if(refundResult.getRefundId() == null){
				throw new RefundMoneyFailException("退款失败！");
			}
		}else if(orders.getPayWay()==PayWay.CASH.toIntValue()){
			userConfig.setCurrentMoney(userConfig.getCurrentMoney()+ordersRefund.getMoney());
			userConfigDAO.update(userConfig);
		}else if(orders.getPayWay()==PayWay.REDEEM.toIntValue()){
			userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney()+ordersRefund.getMoney());
			userConfigDAO.update(userConfig);
		}else if(orders.getPayWay()==PayWay.MEMBER.toIntValue()){
			ShopClient shopClient = shopClientDAO.findClientByUserId(orders.getUserId(),orders.getShopId());
			shopClient.setBalance(shopClient.getBalance()+ordersRefund.getMoney());
			shopClientDAO.update(shopClient);
		}
		
		//更改退款记录信息
		ordersRefund.setWechatRefundNumber(refundResult.getRefundId());
		ordersRefund.setStatus(OrdersRefundStatus.COMPLETE.toIntStatus());
		ordersRefund.setCompleteTime(new Date());
		ordersRefundDAO.update(ordersRefund);
		
		//更改商品订单退款状态
		ordersGoods.setIsRefundMoney(Is.NO.toIntValue());
		ordersGoodsDAO.update(ordersGoods);
		
		//更新订单状态
		List<OrdersGoodsBO> list = ordersGoodsDAO.getOrderGoodsOrderId(orders.getId());
		for(int i=0;i<list.size();i++){
			if(list.get(i).getIsRefundMoney() == Is.NO.toIntValue()){
				flag=false;
				break;
			}
		}
		if(flag){
			orders.setStatus(OrderStatus.FAIL.toIntValue());
			ordersDAO.update(orders);
		}
		
		return result;
	}

	@Override
	public ResultVO getApplyTotal(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		
		if(StringUtils.isNotBlank(systemUserSessionVO.getSystemId())){
			Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
			if (shop == null) {
				throw new ShopNotFoundException("店铺不存在");
			}
			int count = ordersRefundDAO.getApplyTotal(shop.getId());
			result.setData(count);
		}else{
			int count = ordersRefundDAO.getApplyTotal(null);
			result.setData(count);
		}
		return result;
	}

	@Override
	public void updateOrdersRefundComplete() {
		List<OrdersRefund> orList=ordersRefundDAO.findAll();
		for(OrdersRefund or:orList){
			if(DateUtil.getDate(or.getCreatedTime(),10).getTime()<new Date().getTime()){
				or.setStatus(OrdersRefundStatus.SHOP_AGREE.toIntStatus());
				or.setShopDealTime(new Date());
				ordersRefundDAO.update(or);
			}
		}
	}
}
